<?php

namespace app\api\controller;


use app\common\wechat\WXBizMsgCrypt;
use think\Config;
use think\Log;
use think\Validate;
use think\Controller;
use app\common\Base;
use app\api\common\Tools;
use app\api\service\WechatService;

class Wechat extends Controller
{
    public function _initialize()  // 前置验证
    {
        if (isset($_GET['echostr']) and !isset($_GET['data'])) {
            $WS = new WechatService();
            if (!$WS->vailCallBack($_GET)) {
                echo 'Think for Your Watch!';
                exit();
            }
        }
        parent::_initialize();
    }

    /*
     * 公众号客服消息回调接口
     * @Xiao
     */
    public function callback($appid)
    {
        $postStr = file_get_contents("php://input");
        if ($postStr and isset($_GET['timestamp']) and isset($_GET['nonce']) and isset($_GET['encrypt_type']) and isset($_GET['msg_signature']) and isset($_GET['signature'])) {
            $timeStamp = $_GET['timestamp'];
            $nonce = $_GET['nonce'];
            $msg_sign = $_GET['msg_signature'];
            $Encrypt = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA)->Encrypt; // 消息数据

            $SDK = new WXBizMsgCrypt(Config::get('wxopen.token'), Config::get('wxopen.encodeKey'), Config::get('wxopen.appid'));

            $from_xml = sprintf('<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>', $Encrypt);

            $msg = '';
            if ($SDK->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg) == 0) {
                $OPEN = new Open();
                $RES = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA);
                if ($appid == 'wxd101a85aa106f53e' and $RES->ToUserName == 'gh_8dad206e9538') { // 如果是测试账号
                    $QUERY_AUTH_CODE = substr($RES->Content, 16);
                    $Text = $QUERY_AUTH_CODE . '_from_api';
                    $Service = new WechatService();
                    $access_token = $Service->api_query_auth($QUERY_AUTH_CODE)['authorizer_access_token'];
                    $OPEN->sendMessagesToUser($access_token, $Text, 'oV6P70DM0-NBLoiQKb2JISwLhR80', 'text');
                }

                /* 代小程序接收客服消息 wyz_talk_to_user */

                Log::error('++++++++++++++++++++ 客服接口 ++++++++++++++++++');
                Log::error('ToUserName : ' . $RES->ToUserName);
                Log::error('FromUserName : ' . $RES->FromUserName);
                Log::error('CreateTime : ' . $RES->CreateTime);
                Log::error('MsgType : ' . $RES->MsgType);
                Log::error('ToUserName : ' . $RES->ToUserName);
                Log::error('Content : ' . $RES->Content);
                Log::error('MsgId : ' . $RES->MsgId);

                /* 异步通知小程序主接收并回复信息 */


            }
            echo 'success';
        } else {
            echo 'Think for your Watch!';
        }
        exit();
    }

    /*
     * 微信回调入口
     * 事件、消息、统计
     */
    public function index()
    {
        // echo "<xml>
        //       <ToUserName><![CDATA[oazoWv3r1r03ozT2PgMEfgd0LZ7g]]></ToUserName>
        //       <FromUserName><![CDATA[gh_e53d978690fd]]></FromUserName>
        //       <CreateTime>".time()."</CreateTime>
        //       <MsgType><![CDATA[text]]></MsgType>
        //       <Content><![CDATA[你好啊呵呵呵呵]]></Content>
        //   </xml>";
        //   exit();

        $postStr = file_get_contents("php://input");
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); // 消息数据

        $S = new WechatService();
        switch ($postObj->MsgType) {
            case 'event':
                echo $S->Event($postObj);
                exit();
                break;
            case 'text':
                echo $S->Text($postObj);
                exit();
                break;
            default:
                break;
        }

    }

    /*
     *  获取个人微信号绑定小程序回调二维码
     *  @Post : appId
     */
    public function getQrcode($type = null, $data = null)
    {
        $R = new Tools();
        $type = isset($_GET['type']) ? $_GET['type'] : $type;
        $data = isset($_GET['data']) ? $_GET['data'] : $data;
        if (empty($type) or empty($data)) {
            return $R->error('request fail');
        }
        $S = new WechatService();
        switch ($type) {
            case 'setcallback':
                $qrCode_src = $S->creartQrcode('(setWXCallBack)[' . $data . ']', 'scene_str', 'QR_STR_SCENE', 1800, false);
                return $R->success(true, ['src' => $qrCode_src]);
                break;
            default:
                return $R->error('request fail');
                break;
        }
    }

    /*
     * 发送 【新订单模板消息】 模板消息
     *  URL = http://api.suyongw.com/wechat/sendMessage only POST
     *  $_POST['type'] = newOrder /;
     *  $_POST['openid'] = WeChatID;
     *  $_POST['key'] = md5($_POST['type'] . 'suyongkeji' . $_POST['openid']);
     *  $_POST['data'] = '{
     *       "first":{"value":"哈哈，模板消息成功","color":"#000"},
     *       "keyword1":{"value":"你有一个新的订单消息","color":"#000"},
     *       "keyword2":{"value":"2017年8月12日24232","color":"#000"},
     *       "remark":{"value":"另外你还想说些神马？","color":"#000"}
     *    }';
     */
    public function sendMessage($type = null, $openid = null, $data = null, $key = null)
    {
        $R = new Tools();

        $type = $type ? $type : $_POST['type']; // 发送模板消息类型
        $openid = $openid ? $openid : $_POST['openid']; // 接受的微信个人openid
        $data = $data ? $data : $_POST['data']; // 消息内容数据包
        $key = $key ? $key : $_POST['key']; // Key 验证

        if (empty($type) or empty($openid) or empty($data) or empty($key)) {
            return $R->error('request fail');
        };


        // 检测 KEY 是否合法
        if (md5($type . 'suyongkeji' . $openid) != $key) {
            return $R->error('key error');
        }

        switch ($type) {
            case 'newOrder':
                $datas = json_decode($data, true);
                $validate = new Validate([
                    'first' => 'require', // 订单提示对象：客户昵称（如：亲爱的会员）
                    'keyword1' => 'require', // 订单内容：客户App被下单内容（如：鸡腿饭1份）
                    'keyword2' => 'require', // 订单时间 如：2017年8月12日14:10:00
                    'remark' => 'require' // 其他信息 如：当前有2份订单
                ]);
                if (!$validate->check($datas)) {  // 合法性验证
                    return $R->error($validate->getError());
                }
                $S = new WechatService();  // 尝试发送模板消息 
                if ($S->sendMessage_tpl('r4F4Ld5UP58SRjboJrj009NF08dj0ZHPtTr4sRTHb3w', $openid, $datas)) {
                    return $R->success('send success');
                }
                return $R->error('send error');
                break;
            default:
                return $R->error('request fail');
                break;
        }
    }

    // ++++++++++++++++++++++++++++++++++++++++
    // |  @Xiao  Appid secret 验证
    // ++++++++++++++++++++++++++++++++++++++++
    public function validata($appid = null, $secret = null)
    {
        $appid = isset($_GET['appid']) ? $_GET['appid'] : $appid;
        $secret = isset($_GET['secret']) ? $_GET['secret'] : $secret;

        $Tools = new Tools();
        if (empty($appid) or empty($secret)) {
            return $Tools->error('request miss!');
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;
        $Token = json_decode(Base::_requestGet($url), true);
        if (isset($Token['errcode']) and $Token['errcode'] != 0) {
            return $Tools->error('vaildate fail!');
        }
        return $Tools->success('vaildate success!');
    }


}































